package com.dwxt.cdms.listener;

import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.constant.EquipCategory;
import com.dwxt.cdms.constant.TaskMessageData;
import com.dwxt.cdms.constant.WarningType;
import com.dwxt.cdms.dao.CustomerMapper;
import com.dwxt.cdms.dao.HealthWarnRecordMapper;
import com.dwxt.cdms.dao.LbWatchDataMapper;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.service.*;
import com.dwxt.cdms.util.RedisUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    private TaskMessageService taskMessageService;

    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private MedicationRemindService medicationRemindService;

    @Autowired
    private LbWatchDataMapper lbWatchDataMapper;

    @Autowired
    private WarningService warningService;
    @Autowired
    private RelationService relationService;

    /**
     * redis失效后回调函数
     *
     * @param message
     * @param pattern
     */
    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] pattern) {
        super.onMessage(message, pattern);
        String key = new String(message.getBody(), "UTF-8");
        //String channel = new String(message.getChannel(), "UTF-8");
        //是否为消息管理
        TaskMessage taskMessage = taskMessageService.selectById(key);
        if (taskMessage != null) {
            //发送消息
            sendMessage(taskMessage);
            //判断是循环任务还是一次定时任务
            if ("1".equals(taskMessage.getType())) {//循环任务,设置下一次失效时间
                TaskMessageData.setRedisValue(taskMessage);
            }
        }
        //是否为用药提醒
        MedicationRemind medicationRemind = medicationRemindService.selectById(key);
        if (medicationRemind != null) {
            sendMedicationRemind(medicationRemind);
            medicationRemindService.setRedisValue(medicationRemind);
        }
        LbWatchData lbWatchData = lbWatchDataMapper.selectByDeviceMac(key);
        if (lbWatchData != null) {
            lbShutdownWarning(lbWatchData);
        }

    }

    /**
     * @param taskMessage:
     * @return void
     * @Description: 发送消息
     * @author chendq
     * @date 2021/10/18
     */
    public void sendMessage(TaskMessage taskMessage) {
        HealthMessage msg = new HealthMessage();
        msg.setType(taskMessage.getTitle());
        CustomerExample example = new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        if (!"0".equals(taskMessage.getReceiveType())) {//指定了微信或者档案用户
            criteria.andTypeEqualTo(Integer.valueOf(taskMessage.getReceiveType()));
        }
        List<Customer> customers = customerMapper.selectByExample(example);
        for (Customer customer : customers) {
            msg.setCustomerId(customer.getId());
            msg.setId(UUID.randomUUID().toString());
            String name = customer.getName() == null ? "" : customer.getName();
            String content = taskMessage.getContent().replace("username", name);
            msg.setContent(content);
            msg.setCrateTime(new Date());
            healthWarnRecordMapper.insertMessage(msg);
        }
        taskMessageService.updateStatusToFinish(taskMessage);
    }


    public void sendMedicationRemind(MedicationRemind medicationRemind) {
        //判断提醒方式
        String remindType = medicationRemind.getRemindType();
        if (StringUtils.isBlank(remindType)) {
            return;
        }
        if (remindType.contains("小程序")) {
            //小程序
            HealthMessage msg = new HealthMessage();
            msg.setType("用药提醒");
            msg.setContent(medicationRemind.getContent());
            msg.setCustomerId(medicationRemind.getCustomerId());
            msg.setId(UUID.randomUUID().toString());
            msg.setCrateTime(new Date());
            healthWarnRecordMapper.insertMessage(msg);
        } else if (remindType.contains("短信")) {
            //短信

        } else if (remindType.contains("语音")) {

            //语音
        }
    }

    public void lbShutdownWarning(LbWatchData lbWatchData) {
        Date reportTime = lbWatchData.getReportTime();
        long hour = (new Date().getTime() - reportTime.getTime()) / 1000 * 60 * 60;
        if (hour > 50) {
            return;
        }
        warningService.insertWarning(lbWatchData.getCustomerId(), WarningType.SHUTDOWN, lbWatchData.getDeviceMac(), EquipCategory.LB);
        RedisUtil.set(lbWatchData.getDeviceMac(), lbWatchData, 60 * 60 * 24l);
        //小程序消息通知
        Customer customer = customerMapper.selectByPrimaryKey(lbWatchData.getCustomerId());
        String selfName = StringUtil.isBlank(customer.getName()) ? customer.getPhone() : customer.getName();
        String sexs = customer.getSex() == 0 ? "女士" : "先生";
        String hourStr = "";
        if (hour < 25) {
            hourStr = "24";
        }
        if (hour < 50) {
            hourStr = "48";
        }
        //本人
        HealthMessage msg = new HealthMessage();
        msg.setType("关机提醒");
        msg.setContent("尊敬的" + selfName + sexs + "您好：\n" + "安博馨监测到您的手环已关机"+hourStr+"小时。请及时开机，如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
        msg.setCustomerId(customer.getId());
        msg.setId(UUID.randomUUID().toString());
        msg.setCrateTime(new Date());
        healthWarnRecordMapper.insertMessage(msg);
        //关联人
        List<Customer> list = relationService.selectMyManagerCustomer(customer.getId());
        if (list == null || list.size() == 0) {
            return;
        }
        for (Customer relatonCustomer : list) {
            String reName = StringUtil.isBlank(customer.getName()) ? customer.getPhone() : customer.getName();
            String reSexs = customer.getSex() == 0 ? "女士" : "先生";
            HealthMessage msg1 = new HealthMessage();
            msg1.setType("关机提醒");
            msg1.setContent("尊敬的" + reName + reSexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + " 的智能健康手环已关机"+hourStr+"小时，须及时开机。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
            msg1.setCustomerId(relatonCustomer.getId());
            msg1.setId(UUID.randomUUID().toString());
            msg1.setCrateTime(new Date());
            healthWarnRecordMapper.insertMessage(msg1);
        }

    }

}
